package cn.idongjia.task.djexcuter.handler;

import cn.idongjia.task.common.task.ExcuteResult;
import cn.idongjia.task.common.task.Result;
import cn.idongjia.task.common.task.Task;
import cn.idongjia.task.common.util.PojoUtils;
import cn.idongjia.task.djexcuter.mapper.ItemMapper;
import cn.idongjia.task.djexcuter.mapper.TaskMapper;
import cn.idongjia.task.djexcuter.mapper.UserMapper;
import cn.idongjia.task.djexcuter.pojo.Post;
import cn.idongjia.tianji.pojos.Item;
import cn.idongjia.tianji.pojos.User;
import com.baidu.disconf.client.common.annotations.DisconfFile;
import com.baidu.disconf.client.common.annotations.DisconfFileItem;
import com.baidu.disconf.client.common.annotations.DisconfUpdateService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.idongjia.task.common.util.ParamUtil.checkMandatory;
import static cn.idongjia.util.Utils.getCurrentSecond;
import static cn.idongjia.util.Utils.isEmpty;
import static cn.idongjia.task.common.constant.RedisDb.*;

/**
 * Created by renxianlong on 16/4/22.
 */

public class AutoCollectHandler extends AbstractExcuterHandler{
    public static final String PID = "pid";
    public static final String UID = "uid";
    private Logger logger = Logger.getLogger(AutoCollectHandler.class);

    @Resource
    private JedisPool pool;

    @Resource
    private ItemMapper itemMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private TaskMapper taskMapper;

    private String defaultAvatar;

    @Override
    public ExcuteResult excute(Task task) {
        //校验必选参数
        checkMandatory(task,PID,UID);
        String pid = task.getExtParam(PID);
        String uid = task.getExtParam(UID);
        ExcuteResult result = new ExcuteResult();
        Post post = itemMapper.getByPid(pid);
        User user = userMapper.getUserInfoByPojo(Long.parseLong(uid));
        if (null == user || null == post || (post.getType() == 1 && post.getStatus() == 1)) {
            return new ExcuteResult(Result.EXECUTE_FAILED,"用户或分享数据不对,执行异常");
        }

        logger.debug("用户【" + uid + "】收藏" + (post.getType() == 1 ? "分享" : "商品") + "【" + pid + "】");

        long tm = getCurrentSecond();
        taskMapper.collectPost(uid, pid, tm);
        taskMapper.incrCollectCnt(pid);

        incrCount(uid);
        invalidCache("CTP." + pid);

        Map store = new HashMap<>();
        Map newStore = new HashMap<>();
        store.put("uid", uid);
        store.put("tm", tm);
        store.put("un", user.getUsername());
        store.put("avt", isEmpty(user.getAvatar()) ? defaultAvatar : user.getAvatar());

        newStore.putAll(store);
        newStore.put("pid", pid);
        newStore.put("type", post.getType());
        String pic = post.getPictures();
        if (Post.Type.ITEM.get().intValue() == post.getType()) {
            Item item = itemMapper.getItemByPid(post.getPid());
            pic = item.getPictures();
        }
        if (pic.indexOf('[') > -1) {
            List<String> pics = PojoUtils.decodeToObject(List.class, pic);
            pic = pics.get(0);
        }
        newStore.put("img", pic);
        try (Jedis jedis = pool.getResource()) {
            jedis.select(DB4);
            jedis.lpush(genarateKey("like.", pid), PojoUtils.encodeToJson(store));
            jedis.lpush(genarateKey("newcollect", String.valueOf(post.getUid())),
                    PojoUtils.encodeToJson(newStore));
        }

        return result;
    }

    private void incrCount(final String uid) {
        try (Jedis jedis = pool.getResource()) {
            jedis.select(DB2);
            jedis.incr("clcnt.us." + uid);
        }
    }

    private void invalidCache(final String key) {
        try (Jedis jedis = pool.getResource()) {
            jedis.select(DB0);
            jedis.del(key);
        }
    }

    private static String genarateKey(final String key, final String uid) {
        return key + ".lst." + uid;
    }

    public String getDefaultAvatar() {
        return defaultAvatar;
    }

    public void setDefaultAvatar(String defaultAvatar) {
        this.defaultAvatar = defaultAvatar;
    }
}
